package com.oceansoft.mobile.biz.admin.controller;

import static com.oceansoft.mobile.common.Constant.GLOBAL_SESSION;
import static org.springframework.web.bind.annotation.RequestMethod.GET;
import static org.springframework.web.bind.annotation.RequestMethod.POST;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.alibaba.fastjson.JSONObject;
import com.oceansoft.mobile.biz.admin.entity.BasesiteArticleNews;
import com.oceansoft.mobile.biz.admin.entity.SysUser;
import com.oceansoft.mobile.common.Constant;
import com.oceansoft.mobile.common.base.entity.Result;
import io.netty.util.internal.StringUtil;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.support.WebApplicationContextUtils;

import com.alibaba.fastjson.JSON;
import com.oceansoft.mobile.biz.admin.entity.Count;
import com.oceansoft.mobile.biz.admin.service.ICountAdminService;
import com.oceansoft.mobile.common.base.entity.Pager;
import com.oceansoft.mobile.common.base.entity.Query;
import com.oceansoft.mobile.common.dao.ICommonDao;
import com.oceansoft.mobile.common.util.CommonUtilCache;
import com.oceansoft.mobile.weixin.task.SummaryProcessor;
import com.oceansoft.mobile.weixin.util.DateUtil;


@Controller
@RequestMapping("tj/count")
public class CountAdminController {

    @Resource
    private ICountAdminService countAdminService;
    
    @Resource
	private ICommonDao commonDao;
    
    private SummaryProcessor p = null;

    


	/**
     * 后台进入统计
     *
     * @param model
     * @return
     */
    @RequestMapping(value = "count-index", method = GET)
    public String gotocountlList(Model model) {
		return "admin/count/count-list";
    }
	/**
	 * 后台进入统计
	 *
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "fj-count-index", method = GET)
	public String gotocountfjList(Model model,HttpSession session) {
		SysUser user = (SysUser)session.getAttribute(GLOBAL_SESSION);
		model.addAttribute("sourceid","ewm_"+user.getLogin_id());
		return "admin/count/fj-count-show";
	}

    /**
     * 后台进入统计
     *
     * @param model
     * @return
     */
    @RequestMapping(value = "sum-index", method = GET)
    public String gotosumlList(Model model) {
        return "admin/count/sum-list";
    }
    /**
     * 后台进入统计
     *
     * @param model
     * @return
     */
    @RequestMapping(value = "count-info", method = GET)
    public String gotocountInfo(HttpServletRequest request, Model model) {
    	 String start = request.getParameter("start");
	     String end = request.getParameter("end");
	     String id = request.getParameter("id");
	     model.addAttribute("start", start);
	     model.addAttribute("end", end);
	     model.addAttribute("id", id);
        return "admin/count/count-info";
    }
    
    @RequestMapping(value = "count-xzxk", method = GET)
    public String gotocountXzxk(HttpServletRequest request, Model model) {
    	 String start = request.getParameter("start");
	     String end = request.getParameter("end");
	     String whereSQL = "";
	     if(!StringUtil.isNullOrEmpty(start))
	     {
	    	 //whereSQL += " and date_format(t.tjdate,'%Y-%m-%d') >= '"+start+"'";
	    	 whereSQL += " and t.tjdate >= '"+start+"'";
	     }
	     if(!StringUtil.isNullOrEmpty(end))
	     {
	    	 //whereSQL += " and date_format(t.tjdate,'%Y-%m-%d') <= '"+end+"'";
	    	 whereSQL += " and t.tjdate <= '"+end+"'";
	     }
	     String sql = " select a.id,sum(case when a.source='szgaapp'  THEN c else 0 end ) c1,"
	    +" sum(case when a.source!='szgaapp'  THEN c else 0 end ) c2 from ("
	    +" select  t.id,t.source,SUM(t.submitcount) c from t_url_tj t ,t_url_tj_dict d"
	    +" where t.source=d.sourceid and d.isfirst=-1 and  t.id  in (1,2,3,4,5,6,7,8,9,10,11,21,23,24,25,44)" + whereSQL 
	    +" GROUP BY t.id,t.source ) a group by a.id";
	     
	     System.out.println(sql);
	     
	     List list  =  commonDao.loadMapList(sql);
	     model.addAttribute("list", JSON.toJSON(list));
	     model.addAttribute("start", start);
	     model.addAttribute("end", end);
         return "admin/count/xzxk";
    }

    @ResponseBody
    @RequestMapping(value = "countlist", method = GET)
    public Pager gotoCountList(HttpSession session, Query query, HttpServletRequest request) {
        String start = request.getParameter("start");
        String end = request.getParameter("end");

        return countAdminService.findCountList(query, start, end);
    }


    @RequestMapping("/countExport")
    public void decideExport(HttpServletRequest request, HttpSession session, Query query,
                             HttpServletResponse response) throws Exception {
        String start = request.getParameter("start");
        String end = request.getParameter("end");

        Pager pag1 = countAdminService.findSumList(query, start, end);
        Pager pag2 = countAdminService.findCountList(query, start, end);
        Map<String, Object> nqxMap = new LinkedHashMap<String, Object>();
        nqxMap.put("list1",  pag1.getRows());
        nqxMap.put("list2",  pag2.getRows());
        countAdminService.export(request, response, "doc", "wjwtj.xml", nqxMap);
    }


    @ResponseBody
    @RequestMapping(value = "sumlist", method = GET)
    public Pager gotoSumList(HttpSession session, Query query, HttpServletRequest request) {
        query.setSort(query.getSort());
        String start = request.getParameter("start");
        String end = request.getParameter("end");

        return countAdminService.findSumList(query, start, end);
    }

    @ResponseBody
	@RequestMapping(value = "rbtj", method = GET)
	public String rbtj(Model model, HttpServletRequest request) {
		String rq1 = request.getParameter("rq1");
		String rq2 = request.getParameter("rq2");
		String tjid = request.getParameter("tjid");
		//tjid = "53";
		SimpleDateFormat dd=new SimpleDateFormat("yyyy-MM-dd"); 
		if (!org.springframework.util.StringUtils.hasText(rq1)) {
			rq1 = dd.format(DateUtil.getYesterdayDate());
		}
		if (!org.springframework.util.StringUtils.hasText(rq2)) {
			rq2 = rq1;
		}
		// 开始统计数据
		// 1.获取配置文件
		String sql = "select * from t_url_mark ";
		if(org.springframework.util.StringUtils.hasText(tjid))
		{
			sql += " where id="+tjid;
		}
		List<Map<String, Object>> list = commonDao.loadMapList(sql);
		try {
			Date d1 = dd.parse(rq1);
			Date d2 = dd.parse(rq2);
			GregorianCalendar gc=new GregorianCalendar(); 
			gc.setTime(d1); 
			do{
				//统计
				String tjdate = dd.format(gc.getTime());
				System.out.println(tjdate);
				for (Map<String, Object> m : list) {
					Integer id = (Integer) m.get("id");
					String viewurl = (String) m.get("viewurl");
					String submiturl = (String) m.get("submiturl");
					String firstWhere = ""; 
					if(52!=id)
					{
						firstWhere = " and d.isfirst='-1' ";
					}
					//先删除统计日期的数据 
					commonDao.update("delete from t_url_tj where tjdate='"+tjdate+"' and id="+id);
					String tjsql = "insert into t_url_tj "
							    +" select z.sj,	z.id,	a.viewcount,  b.submitcount,	0,	z.sourceid from ("
							    + " select t.id,d.sourceid,'"+tjdate+"' sj from t_url_mark t,t_url_tj_dict d where t.id='"+id+"' "+ firstWhere
							    + " ) z left join "
								+"	(select  '"+id+"' id ,count(1) viewcount,source from t_api_access_log t1 "
								+"	 where t1.url like '"+viewurl+"%' and t1.logdate = '"+tjdate+"' group by  t1.source )a"
								+ " on a.id=z.id and a.source=z.sourceid "
								+"	left join "
								+" (select count(1) submitcount,'"+id+"' id,source  from t_api_access_log t2 where t2.succ='true' and t2.result!='null' and   t2.method='"+submiturl+"' and t2.logdate = '"+tjdate+"' group by  t2.source) b "
								+"	on b.id=z.id and b.source=z.sourceid ";
				   System.out.println(tjsql+";");
				   commonDao.update(tjsql);
				}
				//统计关注人数
				if(StringUtil.isNullOrEmpty(tjid))
				{
					getProcessor().process(tjdate);
				}
				gc.add(5,1); //增加一天
				d1 = gc.getTime();
			}while(!d1.after(d2));//判断是否还能运行
		} catch (ParseException e) {
			e.printStackTrace();
		}
		return "完成统计";
	}
    
    private SummaryProcessor getProcessor()
    {
    	if(null==p)
    	{
    		ServletContext ctx = (ServletContext) CommonUtilCache.getItem("ctx");
    		ApplicationContext app = WebApplicationContextUtils.getWebApplicationContext(ctx); //获取spring上下文！   
    		p = (SummaryProcessor)app.getBean(SummaryProcessor.class) ;
    	}
    	return p;
    }

	public static void main(String[] args) {
		String rq1 = "20160331";
		String rq2 = "20160402";
		SimpleDateFormat dd=new SimpleDateFormat("yyyyMMdd"); 
		try {
			Date d1 = dd.parse(rq1);
			Date d2 = dd.parse(rq2);
			GregorianCalendar gc=new GregorianCalendar(); 
			gc.setTime(d1); 
			do{
				//统计
				String s = dd.format(gc.getTime());
				System.out.println(s);
				gc.add(5,1); //增加一天
				d1 = gc.getTime();
			}while(!d1.after(d2));//判断是否还能运行
		} catch (ParseException e) {
			e.printStackTrace();
		} 
	}
	 @ResponseBody
	    @RequestMapping(value = "countinfo", method = GET)
	    public Pager gotoCountInfo(HttpSession session, Query query, HttpServletRequest request) {
	        String start = request.getParameter("start");
	        String end = request.getParameter("end");
	        String id = request.getParameter("id");
	        	return countAdminService.findCountInfo(query, start, end,id);
	    }
	 @RequestMapping("/showExport")
	    public void showExport(HttpServletRequest request, HttpSession session, Query query,
	                             HttpServletResponse response) throws Exception {
//	        String start = request.getParameter("start");
//	        String end = request.getParameter("end");
//	        String source=request.getParameter("source");
//	        String id=request.getParameter("id");
//	        Map<String, Object> nqxMap = new LinkedHashMap<String, Object>();
//	        if(source==""||source==null)
//	        {
//	 	        Pager<Count> pag1 = countAdminService.findCountshoe(query, start, end, id);
//	 	        List<Count> list= pag1.getRows();
//	 	       nqxMap.put("nqxlist", list);
//	 	       System.out.println(pag1.getRows());
//	        }
//	        else
//	        {
//	        	Pager<Count> pag1 = countAdminService.findCountShowIn(query, start, end, id, source);
//	        	List<Count> list= pag1.getRows();
//		 	     nqxMap.put("nqxlist", list);
//	        }
			 Map<String, Object> nqxMap = new LinkedHashMap<String, Object>();
			 nqxMap.put("nqxlist",session.getAttribute("exportList"));
	        countAdminService.export(request, response, "xls", "count.xml", nqxMap);
	    }

	 /**
	     * 后台进入二维码统计
	     *
	     * @param model
	     * @return
	     */
	    @RequestMapping(value = "count-show", method = GET)
	    public String gotocountShowInfo(HttpServletRequest request, Model model) {
	    	 String start = request.getParameter("start");
		     String end = request.getParameter("end");
		     String id = request.getParameter("id");
		     model.addAttribute("start", start);
		     model.addAttribute("end", end);
		     model.addAttribute("id", id);
		     //获取下拉数据
		     String sql = "select sourceid id,sourceName name from t_url_tj_dict t where t.isfirst='0'";
		     List list = commonDao.loadMapList(sql);
		     model.addAttribute("dict",list);
	         return "admin/count/count-show";
	    }
	    @ResponseBody
	    @RequestMapping(value = "countshoe", method = GET)
	    public Pager gotoC( Query query, HttpServletRequest request) {
	        String start = request.getParameter("bengin");
	        String end = request.getParameter("finial");
	        String id = request.getParameter("id");
	        String source=request.getParameter("source");
	        //System.out.println(start);
	        //System.out.println(end);
	        if(source==""||source==null)
	        {
				Pager p =countAdminService.findCountshoe(query, start, end, id);
				request.getSession().setAttribute("exportList",p.getRows());
	        	return p;
	        }
	        else
	        {
				Pager p =countAdminService.findCountShowIn(query, start, end, id, source,request);

				return p;
	        }
	        
	    }

	/**
	 * 后台进入二维码新增页面
	 *
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "add-ewm", method = GET)
	public String gotoAdd(HttpServletRequest request, Model model) {
		String source = request.getParameter("source");
		model.addAttribute("source", source);
		return "admin/count/add-ewm";
	}
	/**
	 * 表单提交
	 *
	 * @return Result
	 */
	@ResponseBody
	@RequestMapping(value = "ewm/new", method = POST)
	public Result submitProductForm(HttpServletRequest request) {
		String sourceid=request.getParameter("sourceid");
		String sourceName=request.getParameter("sourceName");
		String secondName = request.getParameter("secondName");
		String url = "https://wjw.szgaj.cn/szgawx/micro/redirect/0?source="+sourceid;
		int i = commonDao.getCount("select count(1) from t_url_tj_dict where sourceName='"+sourceName+"' and secondName='"+secondName+"'");
		int k = commonDao.getCount("select count(1) from t_url_tj_dict where sourceid='"+sourceid+"'");
		if(i>0&&k>0){
			return new Result(Result.FAILURE,"所属派出所和所属派出所ID已经存在！");
		}else if(i>0&&k==0){
			return new Result(Result.FAILURE,"所属派出所已经存在！");
		}else if(i==0&&k>0){
			return new Result(Result.FAILURE,"所属派出所ID已经存在！");
		}else{
			try {
				return countAdminService.addewm(sourceid,sourceName,secondName,url);
			} catch (Exception e) {
				e.printStackTrace();
				return new Result(Result.FAILURE);
			}
		}

	}

	/**
	 * 获取secondName
	 * @return Result
	 */
	@ResponseBody
	@RequestMapping(value = "ewm/getsecondName", method = GET)
	public JSONObject getsecondName(HttpServletRequest request) {
		String sourceid = request.getParameter("sourceid");
		String secondName = commonDao.getStringColumn("select secondName from t_url_tj_dict where sourceid = '"+sourceid+"'");
		JSONObject json =new JSONObject();
		json.put("secondName",secondName);
		return json;
	}
}
